/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Moshe
 */
public class RandomHillClimb {

    private Equation equation;
    private int numBits;
    public static BitVector bestVector = null;
    public static long bestTime = 0;
    public static long startTime = 0;
    public static int bestGrade = 0;
    public static long bestNodeCount = 0;
    public static long nodeCount = 0;

    public RandomHillClimb(int bits) {
        equation = AIUI.eq;
        numBits = bits;
    }

    public int Climb(int maxSteps, int maxRepeat) throws IllegalAccessException {

        int currClauseCount = 0;
        int lastClauseCount = 0;
        int currStep = 0;
        nodeCount = 0;
        bestVector = null;
        startTime = System.currentTimeMillis();        

        do {
            lastClauseCount = currClauseCount;

            HillClimb currClimb = new HillClimb(equation, numBits);

            currClauseCount = currClimb.Climb();                

            if (currClauseCount == lastClauseCount) {
                maxRepeat--;
            }
        } while ((++currStep < maxSteps) && (maxRepeat > 0) && (bestGrade < equation.getClauseSize()));

        return bestGrade;
    }

    public int Climb(int maxSteps, int maxRepeat, BitVector vec) throws IllegalAccessException {

        int currClauseCount = vec.getFitness();
        int lastClauseCount = 0;
        int currStep = 0;
        nodeCount = 0;
        bestVector = vec;
        startTime = System.currentTimeMillis();

       do
       {
            lastClauseCount = currClauseCount;

            HillClimb currClimb = new HillClimb(equation, vec);

            currClauseCount = currClimb.Climb();

            if (currClauseCount == lastClauseCount) {
                maxRepeat--;
            }
        } while ((++currStep < maxSteps) && (maxRepeat > 0) && (bestGrade < equation.getClauseSize()));

        return bestGrade;
    }

    public static void UpdateUI()
    {
        SearchResultsProvider.Instance.addResults(bestGrade, bestVector, bestTime, bestNodeCount, true);
    }
}

